layui.define(function (exports) {
    var com = layui.com, $ = layui.jquery, fn = {
        config: {
            url: ''
            , contentType: 'application/json;charset=UTF-8'
            , type: 'GET'
            , showError: true
            , timer: null
            , showLoading: true
            , loadingTime: 400
        }
        , send(opts = {}) {
            opts = $.extend({}, fn.config, opts);
            return new Promise((resolve, reject) => {
                opts.complete = (xhr, status) => {
                    com.hideLoading();
                    clearTimeout(opts.timer);
                    if (status === 'success') {
                        let response = xhr.responseJSON;
                        if (com.stateInterception(response)) {
                            resolve(response);
                        } else {
                            if (fn.config.showError) {
                                layer.msg(response.message);
                            }
                            reject(response);
                        }
                    } else {
                        com.alertWarn(xhr.responseText)
                    }
                };
                if (opts.showLoading && !opts.timer) {
                    opts.timer = setTimeout(() => {
                        opts.timer = null;
                        com.showLoading();
                    }, opts.loadingTime);
                }
                $.ajax(opts)
            });
        }
        , post(url, data) {
            return fn.send({
                type: 'POST'
                , url: url
                , data: JSON.stringify(data || {})
            });
        }
        , get(url, data) {
            return fn.send({
                type: 'GET'
                , url: url
                , data: data || {}
            });
        }
        , postForm(url, data) {
            return fn.send({
                type: 'POST'
                , contentType: 'application/x-www-form-urlencoded'
                , url: url
                , data: data || {}
            });
        }
    }
    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader('token', com.getUser()['token']) , xhr.setRequestHeader('device', 'pc'),
            xhr.setRequestHeader('limitRequestId', com.getLocalStorage('limitRequestId')) 
        }
        , complete: function (xhr, status) {
            if (xhr.responseJSON) {
                com.stateInterception(xhr.responseJSON);
            }
        }
    });
    exports('request', fn);
});